import { post2Server } from '@/services/api';
import { getOpenId } from '@/utils/util';

export default {

  state: {
    gameResult: {},
  },

  reducers: {
    saveGameResult(state, {payload}){
      let list = payload.List.filter(item => item.FragmentNum > 0);
      return {
        ...state,
        gameResult: {
          ...payload,
          List: list,
        },
      }
    },
    giveFragmentReduce(state, {payload}){
      let list = state.gameResult.List.filter(item => {
        if(item.FragmentId === payload.FragmentId){
          item.FragmentNum--;
        }
        return item.FragmentNum > 0;
      });
      return {
        ...state,
        gameResult: {
          ...state.gameResult,
          List: list,
        }
      }
    },
    mergeFragmentReduce(state, {payload}){
      let list = state.gameResult.List.filter(item => {
        if(item.ImageId === payload.ImageId){
          item.FragmentNum--;
        }
        return item.FragmentNum > 0;
      });
      return {
        ...state,
        gameResult: {
          ...state.gameResult,
          List: list,
          DoneNum: state.gameResult.DoneNum + 1,
        }
      }
    }
  },

  effects: {
    *fetchGameResult(payload, { call, put, select }){
      const openId = yield select(getOpenId);
      if(openId){
        const response = yield call(post2Server, 'GMInfoQryByUser.do', { OpenId: openId});
        yield put({
          type: 'saveGameResult',
          payload: response
        });
        return response;
      }
    },
    *giveFragment({payload}, { call, put, select }){
      const openId = yield select(getOpenId);
      const response = yield call(post2Server, 'GMFragmentGive.do', {
        ...payload,
        OpenId: openId,
      });
      if(response){
        yield put({
          type: 'giveFragmentReduce',
          payload,
        });
      }
      return response;
    },
    *mergeFragment({payload}, { call, put, select }){
      const openId = yield select(getOpenId);
      const response = yield call(post2Server, 'GMFragmentMerge.do', {
        ...payload,
        OpenId: openId,
      });
      if(response){
        yield put({
          type: 'mergeFragmentReduce',
          payload,
        });
        return response;
      }
    }
  },

}
